<?php

namespace App\Http\Controllers\Api\Admin;

use App\AboutUs;
use App\Banner;
use App\Classify;
use App\DiscountSalesRule;
use App\Enterprise;
use App\EnterpriseAdmin;
use App\EnterpriseApply;
use App\Http\Services\AdminManager;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\MerchantManager;
use App\Merchant;
use App\MerchantMedicine;
use App\MerchantStaff;
use App\OrderItem;
use App\Orders;
use App\Role;
use App\User;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use http\Message;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class EnterpriseController extends Controller
{
    /**
     * 获取商家列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit   = $request->get('limit') ?? 20;
        $page    = $request->get('page') ?? 1;
        $keyword = $request->get('keyword') ?? '';
        $status  = $request->get('status');

        $pageInfo = [
            'limit'     => $limit,
            'page'      => $page,
            'keyword'   => $keyword,
            'status'    => $status
        ];

        /** @var Enterprise $enterprise */
        $enterpriseList = Enterprise::whereNull('deleted_at');

        if($keyword != ''){
            $userIds = User::where('phone','like','%'.trim($keyword).'%')->orWhere('admin_name','like','%'.trim($keyword).'%')->whereRole(2)->pluck('id');

            $enterpriseIds = EnterpriseAdmin::whereIn('user_id',$userIds)->pluck('enterprise_id');

            $enterpriseList->whereIn('id',$enterpriseIds)->orWhere('legal_person','like','%'.trim($keyword).'%')->orWhere('company_name','like','%'.trim($keyword).'%');
        }

        if(is_numeric($status)){
            $enterpriseList->whereStatus($status);
        }

        $pageInfo['total'] = $enterpriseList->count();

        $enterpriseList = $enterpriseList->orderByDesc('id')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($enterpriseList) > 0){
            foreach ($enterpriseList as $enterprise) {
                $enterprise->business_license_img_url = FileManager::getImgUrl($enterprise->business_license_img_id);

                $enterprise->username = '';
                $enterprise->phone = '';
                $enterprise->admin_name = '';
                $enterprise->merchant_token = '';
                $enterpriseAdmin = EnterpriseAdmin::whereEnterpriseId($enterprise->id)->first();
                if($enterpriseAdmin){
                    $enterpriseAdminUser = User::whereId($enterpriseAdmin->user_id)->first();
                    if($enterpriseAdminUser){
                        $enterprise->username = $enterpriseAdminUser->username;
                        $enterprise->phone = $enterpriseAdminUser->phone;
                        $enterprise->admin_name = $enterpriseAdminUser->admin_name;

                        $userMark = $enterpriseAdminUser->user_key;

                        $token = CryptoJSAES::encrypt($userMark,env('AES_KEY'));

                        $enterprise->merchant_token = $token;
                    }
                }

                if($enterprise->status == 1){
                    $enterprise->status_name = '开启';
                }else{
                    $enterprise->status_name = '关闭';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $enterpriseList,'page_info' => $pageInfo]);
    }

    /**
     * 获取商家详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $enterprise = Enterprise::whereId($id)->first();
        if($enterprise){
            $enterprise->business_license_img_url = FileManager::getImgUrl($enterprise->business_license_img_id);

            $enterpriseAdminUser = null;
            $enterpriseAdmin = EnterpriseAdmin::whereEnterpriseId($enterprise->id)->first();
            if($enterpriseAdmin){
                $enterpriseAdminUser = User::whereId($enterpriseAdmin->user_id)->first();
            }

            $enterprise->enterprise_admin_info = $enterpriseAdminUser;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $enterprise]);
    }

    /**
     * 编辑商家
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setEnterprise(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name                    = $request->input('name') ?? '';
        $contactPerson           = $request->input('contact_person') ?? '';
        $contact                 = $request->input('contact') ?? '';
        $companyName             = $request->input('company_name') ?? '';
        $UnifiedSocialCreditCode = $request->input('Unified_social_credit_code') ?? '';
        $businessLicenseImgId    = $request->input('business_license_img_id') ?? 0;
        $legalPerson             = $request->input('legal_person') ?? '';
        $endTime                 = $request->input('end_time') ?? NULL;
        $username                = $request->input('username') ?? '';
        $password                = $request->input('password') ?? '';
        $adminName               = $request->input('admin_name') ?? '';
        $phone                   = $request->input('phone') ?? '';
        $id                      = $request->input('id') ?? '';

        if($companyName == '')
            return response()->json(['level' => 'error','message' => '请输企业名称']);

        if($legalPerson == '')
            return response()->json(['level' => 'error','message' => '请填写法人名称']);

        if($UnifiedSocialCreditCode == '')
            return response()->json(['level' => 'error','message' => '请填写统一社会信用代码']);

        $uniformSocialCreditCodeVerification = CommonManager::uniformSocialCreditCodeVerification($UnifiedSocialCreditCode);
        if(!$uniformSocialCreditCodeVerification)
            return response()->json(['level' => 'error','message' => '统一社会信用代码格式错误']);

        if($username == '')
            return response()->json(['level' => 'error','message' => '请填写账号']);

        $merchantExist = Enterprise::whereUnifiedSocialCreditCode($UnifiedSocialCreditCode)->first();

        $usernameExists = User::whereUsername($username)->first();

        if($phone != '' && !is_null($phone)){
            $phoneVerification = CommonManager::phoneVerification(trim($phone));
            if(!$phoneVerification)
                return response()->json(['level' => 'error','message' => '手机号格式不正确']);

            $isPhone = User::wherePhone(trim($phone))->whereIn('role',[2,3])->first();
        }

        $enterprise = Enterprise::whereId($id)->first();

        if(!$enterprise){
            if($password == '')
                return response()->json(['level' => 'error','message' => '请填写密码']);

            if($merchantExist)
                return response()->json(['level' => 'error','message' => '统一社会信用代码已被使用']);

            if($usernameExists)
                return response()->json(['level' => 'error','message' => '该账号已被注册']);

            if($phone != '' && !is_null($phone)){
                if($isPhone)
                    return response()->json(['level' => 'error','message' => '当前手机号已被使用']);
            }

            $newEnterprise = new Enterprise();
            $newEnterprise->name                          = $name;
            $newEnterprise->contact                       = $contact;
            $newEnterprise->contact_person                = $contactPerson;
            $newEnterprise->company_name                  = $companyName;
            $newEnterprise->Unified_social_credit_code    = $UnifiedSocialCreditCode;
            $newEnterprise->legal_person                  = $legalPerson;
            $newEnterprise->business_license_img_id       = $businessLicenseImgId;
            $newEnterprise->end_time                      = $endTime;
            $newEnterprise->status                        = 1;
            $newEnterprise->save();

            $newMerchantUser = MerchantManager::signUp($username,$password,$phone,$adminName);

            $enterpriseAdmin = new EnterpriseAdmin();
            $enterpriseAdmin->user_id       = $newMerchantUser->id;
            $enterpriseAdmin->enterprise_id = $newEnterprise->id;
            $enterpriseAdmin->save();

            $merchantAdmin = Role::whereName('merchant_admin')->first();
            if($merchantAdmin){
                $merchantAdminExists = DB::table('role_user')->where('user_id',$newMerchantUser->id)->where('role_id',$merchantAdmin->id)->first();
                if(!$merchantAdminExists){
                    DB::table('role_user')->insert(['user_id' => $newMerchantUser->id,'role_id' => $merchantAdmin->id]);
                }
            }
        }else{
            if($merchantExist && ($merchantExist->id != $enterprise->id))
                return response()->json(['level' => 'error','message' => '统一社会信用代码已被使用']);

            $enterpriseAdminIds = EnterpriseAdmin::whereEnterpriseId($enterprise->id)->first();

            if($usernameExists && ($enterpriseAdminIds && $usernameExists->id != $enterpriseAdminIds->user_id))
                return response()->json(['level' => 'error','message' => '该用户已被注册']);

            if($phone != '' && !is_null($phone)){
                if($isPhone && ($enterpriseAdminIds && $isPhone->id != $enterpriseAdminIds->user_id))
                    return response()->json(['level' => 'error','message' => '当前手机号已被使用']);
            }

            $enterprise->name                          = $name;
            $enterprise->contact                       = $contact;
            $enterprise->contact_person                = $contactPerson;
            $enterprise->company_name                  = $companyName;
            $enterprise->Unified_social_credit_code    = $UnifiedSocialCreditCode;
            $enterprise->legal_person                  = $legalPerson;
            $enterprise->business_license_img_id       = $businessLicenseImgId;
            $enterprise->end_time                      = $endTime;
            $enterprise->status                        = 1;
            $enterprise->save();

            if($enterpriseAdminIds){
                $enterpriseAdminUser = User::whereId($enterpriseAdminIds->user_id)->first();
                if($enterpriseAdminUser){
                    $enterpriseAdminUser->username   = $username;

                    if(!empty($password))
                        $enterpriseAdminUser->password = bcrypt($password);

                    $enterpriseAdminUser->phone      = $phone;
                    $enterpriseAdminUser->admin_name = $adminName;
                    $enterpriseAdminUser->save();
                }
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $enterprise]);
    }

    /**
     * 改变商家状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeEnterpriseStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $enterprise = Enterprise::whereId($id)->first();
        if(!$enterprise)
            return response()->json(['level' => 'error','message' => '该商家不存在']);

        if($enterprise->status == 1){
            $enterprise->status = 0;
        }else{
            $enterprise->status = 1;
        }

        $enterprise->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $enterprise]);
    }

    /**
     * 删除商家
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delEnterprise(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $enterprise = Enterprise::whereId($id)->first();
        if(!$enterprise)
            return response()->json(['level' => 'error','message' => '该商家不存在']);

        $enterpriseAdminList = EnterpriseAdmin::whereEnterpriseId($enterprise->id)->get();
        if(count($enterpriseAdminList) > 0){
            foreach ($enterpriseAdminList as $enterpriseAdmin) {
                User::whereId($enterpriseAdmin->user_id)->delete();
                $enterpriseAdmin->delete();
            }
        }

        $merchantList = Merchant::whereEnterpriseId($enterprise->id)->get();
        if(count($merchantList) > 0){
            foreach ($merchantList as $merchant) {
                $enterpriseStaffList = MerchantStaff::whereMerchantId($merchant->id)->get();
                if(count($enterpriseStaffList) > 0){
                    foreach ($enterpriseStaffList as $enterpriseStaff) {
                        User::whereId($enterpriseStaff->user_id)->delete();
                        $enterpriseStaff->delete();
                    }
                }

                Classify::whereMerchantId($merchant->id)->delete();

                MerchantMedicine::whereMerchantId($merchant->id)->delete();
            }
        }

        User::whereEnterpriseId($enterprise->id)->whereRole(0)->delete();

        $orderList = Orders::whereEnterpriseId($enterprise->id)->get();
        if(count($orderList) > 0){
            foreach ($orderList as $order){
                OrderItem::whereOrderId($order->id)->delete();
                $order->delete();
            }
        }

        DiscountSalesRule::whereEnterpriseId($enterprise->id)->first();

        AboutUs::whereEnterpriseId($enterprise->id)->delete();

        $enterprise->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $enterprise]);
    }

    /**
     * 获取商家申请列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseApplyList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit   = $request->get('limit') ?? 20;
        $page    = $request->get('page') ?? 1;
        $keyword = $request->get('keyword') ?? '';
        $review  = $request->get('review') ?? '';

        $pageInfo = [
            'limit'     => $limit,
            'page'      => $page,
            'keyword'   => $keyword,
        ];

        /** @var EnterpriseApply $enterpriseApply */
        $enterpriseApplyList = EnterpriseApply::whereNull('deleted_at');

        if($keyword != ''){
            $userIds = User::where('phone','like','%'.trim($keyword).'%')->orWhere('admin_name','like','%'.trim($keyword).'%')->whereRole(2)->pluck('id');

            $enterpriseApplyList->whereIn('user_id',$userIds)->orWhere('company_name','like','%'.trim($keyword).'%');
        }

        if($review !== ''){
            $enterpriseApplyList->whereReview($review);
        }

        $pageInfo['total']   = $enterpriseApplyList->count();

        $enterpriseApplyList = $enterpriseApplyList->orderByDesc('created_at')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($enterpriseApplyList) > 0){
            foreach ($enterpriseApplyList as $enterpriseApply) {
                $user = User::whereId($enterpriseApply->user_id)->first();

                $enterpriseApply->user_info = $user;

                if($enterpriseApply->review == 1){
                    $enterpriseApply->review_name = '通过';
                }elseif($enterpriseApply->review == 2){
                    $enterpriseApply->review_name = '拒绝';
                }else{
                    $enterpriseApply->review_name = '待审核';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $enterpriseApplyList,'page_info' => $pageInfo]);
    }

    /**
     * 获取商家申请详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseApplyDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = $request->get('id') ?? 0;

        $enterpriseApply = EnterpriseApply::whereId($id)->first();
        if($enterpriseApply){
            $enterpriseApply->business_license_img_url = FileManager::getImgUrl($enterpriseApply->business_license_img_id);

            $user = User::whereId($enterpriseApply->user_id)->first();

            $enterpriseApply->enterprise_admin_info = $user;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $enterpriseApply]);
    }

    /**
     * 商家审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function enterpriseReview(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id   = $request->get('id') ?? 0;
        $type = $request->get('type') ?? 'refuse';

        $enterpriseApply = EnterpriseApply::whereId($id)->first();
        if(!$enterpriseApply)
            return response()->json(['level' => 'error','message' => '商家申请不存在']);

        if($enterpriseApply->review == 1)
            return response()->json(['level' => 'error','message' => '审核已通过']);

        if($enterpriseApply->review == 2)
            return response()->json(['level' => 'error','message' => '审核已拒绝']);

        if($type == 'pass'){
            /** @var Enterprise $enterpriseInfo */
            $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($enterpriseApply->user_id);
            if(!$enterpriseInfo){
                $newEnterpriseInfo = new Enterprise();
                $newEnterpriseInfo->name                       = $enterpriseApply->name;
                $newEnterpriseInfo->contact                    = $enterpriseApply->contact;
                $newEnterpriseInfo->contact_person             = $enterpriseApply->contact_person;
                $newEnterpriseInfo->company_name               = $enterpriseApply->company_name;
                $newEnterpriseInfo->Unified_social_credit_code = $enterpriseApply->Unified_social_credit_code;
                $newEnterpriseInfo->legal_person               = $enterpriseApply->legal_person;
                $newEnterpriseInfo->business_license_img_id    = $enterpriseApply->business_license_img_id;
                $newEnterpriseInfo->status                     = 1;
                $newEnterpriseInfo->save();

                $enterpriseAdmin = new EnterpriseAdmin();
                $enterpriseAdmin->user_id       = $enterpriseApply->user_id;
                $enterpriseAdmin->enterprise_id = $newEnterpriseInfo->id;
                $enterpriseAdmin->save();

                $merchantAdmin = Role::whereName('merchant_admin')->first();
                if($merchantAdmin){
                    $merchantAdminExists = DB::table('role_user')->where('user_id',$enterpriseApply->user_id)->where('role_id',$merchantAdmin->id)->first();
                    if(!$merchantAdminExists){
                        DB::table('role_user')->insert(['user_id' => $enterpriseApply->user_id,'role_id' => $merchantAdmin->id]);
                    }
                }
            }else{
                $enterpriseInfo->name                       = $enterpriseApply->name;
                $enterpriseInfo->contact                    = $enterpriseApply->contact;
                $enterpriseInfo->contact_person             = $enterpriseApply->contact_person;
                $enterpriseInfo->company_name               = $enterpriseApply->company_name;
                $enterpriseInfo->Unified_social_credit_code = $enterpriseApply->Unified_social_credit_code;
                $enterpriseInfo->legal_person               = $enterpriseApply->legal_person;
                $enterpriseInfo->business_license_img_id    = $enterpriseApply->business_license_img_id;
                $enterpriseInfo->status                     = 1;
                $enterpriseInfo->save();
            }

            $enterpriseApply->review = 1;
            $enterpriseApply->save();
        }elseif($type == 'refuse'){
            $enterpriseApply->review = 2;
            $enterpriseApply->save();
        }else{
            return response()->json(['level' => 'error','message' => '参数错误']);
        }

        return response()->json(['level' => 'success','message' => '操作成功','data' => $enterpriseApply]);
    }
}
